<template>
    <rx-dialog
        order="button"
        btnalign="center"
        class="dialog"
        @handOk="handleSubmit"
        @cancel="cancel"
    >
        <rx-layout>
            <div slot="center">
        <a-tabs default-active-key="1">
            <a-tab-pane key="1" :tab="i18n('portalMobile.grid','栏目')">
                <div class="InsPortaMobileIconfont">
                    <a-form-model layout="vertical" >
                        <div v-if="type!='process'">
                            <!-- 栏目-->
                            <a-form-model-item style="margin-bottom: 5px" :label="i18n('portalMobile.columnType','栏目类型')">
                                <a-select
                                    v-model="InitSubItem.routeName"
                                    :placeholder="i18n('portalMobile.selMenuType','请选择菜单类型')"
                                    :options="options"
                                >
                                </a-select>
                            </a-form-model-item>

                            <!-- 选择应用 -->
                            <a-form-model-item v-if="isCanSelectApp" style="margin-bottom: 5px" :label="i18n('portalMobile.selectApp','选择应用')">
                                <rx-search-app @change="appChange" v-model="InitSubItem.appId">
                                </rx-search-app>
                            </a-form-model-item>
                            <!-- 自定义 -->
                            <div v-if="InitSubItem.routeName =='custom'">
                                <a-form-model-item style="margin-bottom: 5px" :label="$ti18('rxList.title','标题')">
                                    <a-input v-model="InitSubItem.title" @change="updateI18nName(InitSubItem,'title')"
                                             :placeholder="$ti18('rxList.title','请输入标题','','input')">
                                        <my-icon slot="addonAfter" type="iconearth-full" @click="editI18nName(InitSubItem,'title')"/>
                                    </a-input>
                                </a-form-model-item>
                                <a-form-model-item style="margin-bottom: 5px" :label="i18n('portalMobile.customColumn','自定义组件')">
                                    <div class="InsPortaMobileIconfont-programa">
                                        <a-input style="width: 237px;margin-right: 10px;" v-model="InitSubItem.customModule"></a-input>
                                        <a-tooltip style="margin-top: 10px;cursor: pointer">
                                            <template slot="title" style="width:400px;">
                                               页面自定义路径：views/customPage/demo/demo.vue;
                                               自定义组件填写：demo/demo.vue;
                                            </template>
                                            <a-icon type="question-circle-o"/>
                                        </a-tooltip>
                                    </div>
                                </a-form-model-item>
                            </div>
                            <!--url-->
                            <div v-else-if="InitSubItem.routeName =='IFrame'">
                                <a-form-model-item style="margin-bottom: 5px" :label="$ti18('rxList.title','标题11')">
                                    <a-input v-model="InitSubItem.title" @change="updateI18nName(InitSubItem,'title')"
                                             :placeholder="$ti18('rxList.title','请输入标题','','input')">
                                        <my-icon slot="addonAfter" type="iconearth-full" @click="editI18nName(InitSubItem,'title')"/>
                                    </a-input>
                                </a-form-model-item>
                                <a-form-model-item style="margin-bottom: 5px" label="URL">
                                    <a-input v-model="subItem.url"></a-input>
                                </a-form-model-item>
                            </div>
                            <!-- 流程 -->
                            <a-form-model-item v-else-if="InitSubItem.routeName=='process'" style="margin-bottom: 5px" :label="i18n('portalMobile.columnEntry','栏目入口')">
                                <div class="InsPortaMobileIconfont-programa">
                                    <a-input v-model="InitSubItem.title"></a-input>
                                    <a-button @click="processDefinition(InitSubItem)">{{$ti18('rxList.select','选择')}}</a-button>
                                </div>
                            </a-form-model-item>
                            <!-- 单据列表 -->
                            <div v-else-if="InitSubItem.routeName =='CustomList'">
                                <a-form-model-item style="margin-bottom: 5px" :label="i18n('portalMobile.columnEntry','栏目入口')">
                                    <div class="InsPortaMobileIconfont-programa">
                                        <a-input v-model="InitSubItem.title"></a-input>
                                        <a-button @click="chooseData(InitSubItem)">{{$ti18('rxList.select','选择')}}</a-button>
                                    </div>
                                </a-form-model-item>
                                <a-form-model-item v-if="dataAuthAry.length>0" style="margin-bottom: 5px" :label="i18n('portalMobile.dataPermission','数据权限')">
                                    <a-select v-model="InitSubItem.pmtAlias"
                                              :options="dataAuthAry"
                                              :allowClear="true"
                                    >
                                    </a-select>
                                </a-form-model-item>
                            </div>
                            <!-- 自定义页面栏目 -->
                            <a-form-model-item v-else-if="InitSubItem.routeName=='customColumn'" style="margin-bottom: 5px" :label="i18n('portalMobile.customColumnTitle','自定义页面栏目')">
                                <div class="InsPortaMobileIconfont-programa">
                                    <a-input v-model="InitSubItem.title"></a-input>
                                    <a-button @click="chooseData(InitSubItem)">{{$ti18('rxList.select','选择')}}</a-button>
                                </div>
                            </a-form-model-item>
                            <!-- 页面定制 -->
                            <a-form-model-item v-else-if="InitSubItem.routeName=='customView'" style="margin-bottom: 5px" :label="i18n('portalMobile.pageCustom','页面定制')">
                                <div class="InsPortaMobileIconfont-programa">
                                    <a-input v-model="InitSubItem.title"></a-input>
                                    <a-button @click="openCustomView(InitSubItem)">{{$ti18('rxList.select','选择')}}</a-button>
                                </div>
                            </a-form-model-item>
                            <!-- 自定义JS方法 -->
                            <a-form-model-item v-else-if="InitSubItem.routeName=='customFun'" style="margin-bottom: 5px" :label="i18n('portalMobile.customFun','自定义JS方法')">
                                <div class="InsPortaMobileIconfont-programa">
                                    <div class="InsPortaMobileIconfont-programa">
                                        <a-input v-model="InitSubItem.JSScript"></a-input>
                                        <a-button @click="openCustomFunEdit(InitSubItem)">{{i18n('portalMobile.dispose','配置')}}</a-button>
                                    </div>
                                </div>
                            </a-form-model-item>
                            <a-form-model-item v-else style="margin-bottom: 5px" :label="i18n('portalMobile.columnEntry','栏目入口')">
                                <div class="InsPortaMobileIconfont-programa">
                                    <a-input v-model="InitSubItem.title"></a-input>
                                    <a-button @click="chooseData(InitSubItem)">{{$ti18('rxList.select','选择')}}</a-button>
                                </div>
                            </a-form-model-item>
                        </div>
                        <a-form-model-item v-if="types.contains(type) && !ignoreTypes.contains(InitSubItem.routeName)" style="margin-bottom: 5px" :label="i18n('portalMobile.languageConf','多语言标题配置')">
                            <a-input v-model="InitSubItem.title" @change="updateI18nName(InitSubItem,'title')">
                                <my-icon slot="addonAfter" type="iconearth-full" @click="editI18nName(InitSubItem,'title')"/>
                            </a-input>
                        </a-form-model-item>
                            <div v-if="stylize=='img'">
                                <a-upload-dragger
                                    class="self-dragger"
                                    :file-list="fileList"
                                    :directory="false"
                                    :before-upload="beforeUpload"
                                    :customRequest="()=>{}"
                                >
                                    <p v-if="InitSubItem.imgId">
                                        <img class="initSubItem-img" :src="getFilePath(InitSubItem.imgId)" alt="photo"></img>
                                    </p>
                                    <p v-else>
                                        <my-icon class="upicon" type="iconicon_update"></my-icon>
                                    </p>
                                    <p  class="ant-upload-hint">
                                        <span class="up-title">{{i18n('msa.selectColumnImage','选择栏目图片')}}<br/>{{i18n('msa.pictureSize','图片要求')}}</span>
                                    </p>
                                </a-upload-dragger>
                            </div>
                            <div v-else>
                                <a-form-model-item style="margin-bottom: 5px" label="备注">
                                    <a-input v-model="InitSubItem.notes"></a-input>
                                </a-form-model-item>
                                <rx-icon @certainIcon="certainIcon" :system="InitSubItem.system" :bgColor="InitSubItem.bgColor" :icon="InitSubItem.icon"></rx-icon>
                            </div>
                    </a-form-model>
                </div>
            </a-tab-pane>
            <a-tab-pane key="2" :tab="i18n('portalMobile.authority','权限')" force-render>
                <rx-jurisdiction style="padding: 10px" v-model="subItem.permissions"></rx-jurisdiction>
            </a-tab-pane>
        </a-tabs>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>
import {Dialog,RxDialog,Util,TokenUtil,App,JsConstant} from "@lowcode/jpaas-common-lib"
import DialogBox from "@/assets/js/DialogBox";
import UreportListDialog from "@/views/modules/form/core/UreportListDialog";
import AppDialog from "@/views/modules/portal/core/AppDialog";
import FormApi from "@/views/modules/form/core/js-comps/api/FormApi";
import FormBoPermissionApi from "@/api/form/core/formBoPermission";
import CustomPageColumnDialog from "@/views/modules/portal/core/CustomPageColumnDialog";
import RxIcon from "@/components/rxComponent/rx-icon";
import RxJurisdiction from "@/components/rxComponent/rx-jurisdiction";
import CustomViewDialog from "@/views/modules/form/core/dialog/CustomViewDialog";
import PortalJSMonacoEdit from "@/views/modules/form/core/dialog/PortalJSMonacoEdit.vue";
import RxSearchApp from "@/views/modules/share/rx-search-app";


export default {
    name: "InsPortaMobileIconfont",
    mixins:[App],
    props:[ 'subItem','index','layerid','destroy','lydata','stylize','type'],
    components:{
        RxDialog,
        RxIcon,
        RxSearchApp,
        RxJurisdiction,
        PortalJSMonacoEdit
    },
    data(){
        return{
            i18nDefault:process.env.VUE_APP_LANGUAGE,
            i18nCurrent:"",
            isInitI18n:false,
            types:['process','grid','tab','largeScreen'],
            ignoreTypes:['custom','IFrame'],
            dataAuthAry:[],
            backgroundList:['linear-gradient(0deg,#ec9721 0%, #f3cb51 100%)',
                'linear-gradient(0deg,#f3552b 0%,#fc8b76 100%)',
                'linear-gradient(0deg,#20bb78 0%,#85e7a1 100%)',
                'linear-gradient(0deg,#2b76f3 0%,#6db6fb 100%)',
                'linear-gradient(0deg, #fe7f5f 0%,#feb079 100%)',
                'linear-gradient(0deg,#08beb5 0%,#50dda1 100%)',
                'linear-gradient(0deg,#7598ff 0%,#8c94ff 100%)',
                'linear-gradient(0deg,#9529e1 0%,#e76ff3 100%)'],
            InitSubItem:this.subItem,
            options: [
                {
                    label: this.i18n('portalMobile.startForm','流程方案'),
                    value: 'StartForm',
                },
                {
                    label: this.i18n('portalMobile.customForm','表单方案'),
                    value: 'CustomForm',
                },
                {
                    label: this.i18n('portalMobile.customList','单据列表'),
                    value: 'CustomList',
                },
                {
                    label: this.i18n('portalMobile.ureport','ureport报表'),
                    value: 'rxUreport',
                },
                {
                    label: this.i18n('portalMobile.process','流程办理'),
                    value: 'process',
                },
                {
                    label: this.i18n('portalMobile.custom','自定义'),
                    value: 'custom',
                },{
                    label: 'URL',
                    value: 'IFrame'
                },
                {
                  label: this.i18n('portalMobile.customColumnTitle','自定义页面栏目'),
                  value: 'customColumn'
                },
                {
                  label: this.i18n('portalMobile.pageCustom','页面定制'),
                  value: 'customView'
                },
                {
                  label: this.i18n('portalMobile.appId','应用'),
                  value: 'appPortal'
                },
                {
                    label: this.i18n('portalMobile.customFun','自定义JS方法'),
                    value: 'customFun'
                }

            ],
            fileList:[],
            application: {label: this.$ti18('rxForm.appId','应用'), value: 'appPortal'},
            appId: "",
            isCanSelectApp:false,
            isPlatform:false,
            canSelAppRouters:["StartForm", "CustomForm", "CustomList", "rxUreport", "process", "customView","customFun"]
        }
    },
    mounted() {
        this.getCurrentI18n();
        this.loadInitTitleVal();
        if(this.InitSubItem.bgColor && !this.InitSubItem.bgColor.includes('linear-gradient')){
            this.InitSubItem.bgColor = "linear-gradient(0deg,#2b76f3 0%,#6db6fb 100%)"
        }
        if(this.InitSubItem.routeName=="CustomList"){
            var queryAppId=""
            if (this.InitSubItem.appId && this.InitSubItem.appId.length>0){
                queryAppId=this.InitSubItem.appId[0].value;
            }
            this.handDataAuths(this.InitSubItem.key,queryAppId);
        }

        this.appId = this.curApp.appId;
        if (!this.curApp.appId || this.curApp.appId =='0'){
            this.isPlatform=true;
            //this.isCanSelectApp=true
        }else{
            //如果是在应用内，栏目类型屏蔽 应用选项
            this.options=this.options.filter(item=>item.value!="appPortal")
        }
    },
    methods:{
        i18n(name,text,key){
            return this.$ti18(name,text,"insPortalDef",key);
        },
        appChange(){
            this.InitSubItem.title="";
            this.InitSubItem.i18nJson=""
        },
        loadInitTitleVal(){
            if(!this.types.contains(this.type)){
                return;
            }
            this.isInitI18n=true;
            if(!this.InitSubItem.i18nJson){
                this.isInitI18n=false;
                return;
            }
            let i18nJson =JSON.parse(this.InitSubItem.i18nJson);
            let val=i18nJson[this.i18nCurrent];
            if(!val){
                this.isInitI18n=false;
                return;
            }
            this.InitSubItem.title=val;
            this.isInitI18n=false;
        },
        getCurrentI18n(){
            this.i18nCurrent= window.localStorage.getItem("language");
            if(!this.i18nCurrent){
                this.i18nCurrent=this.i18nDefault;
            }
        },
        updateI18nName(record,text) {
            let i18nJson=this.getI18nJson(record,text);
            record[text] = i18nJson[this.i18nCurrent];
            record.i18nJson=JSON.stringify(i18nJson);
        },
        getI18nJson(row,text){
            let i18nJson={};
            let i18nConf =row.i18nJson;
            if(i18nConf){
                i18nJson=i18nConf
                if (typeof i18nConf == "string"){
                    i18nJson=JSON.parse(i18nConf);
                }
                let val=i18nJson[this.i18nCurrent];
                if(!val || !this.isInitI18n){
                    i18nJson[this.i18nCurrent]=row[text];
                }
            }else {
                i18nJson[this.i18nCurrent] = row[text];
                i18nJson[this.i18nDefault] = row[text];
            }
            return i18nJson;
        },
        editI18nName(record,text) {
            let self_ = this;
            let conifg = {
                curVm: this,
                widthHeight: ['800px', '600px'],
                data: {
                    i18nJson: this.getI18nJson(record,text)
                }
            }
            Dialog.openI18nDialog(conifg, function (action, data) {
                record[text] = data[self_.i18nCurrent];
                record.i18nJson=JSON.stringify(data);
            });
        },

        getFilePath(fileId){
            let token = TokenUtil.getToken();
            fileId=Util.encryptWord(fileId);
            return "/api/api-system/system/core/sysFile/previewFile?fileId=" + fileId + "&accessToken=" + token;
        },
        beforeUpload(file) {
            this.fileList = [file];
            let timestamp = new Date().getTime();
            let formdata = new FormData();
            formdata.append('files', file);
            formdata.append("time", Util.encryptWord(timestamp,true));
            let self = this;
            FormApi.upload(formdata).then(res => {
              self.InitSubItem['imgId'] = res.data[0].fileId;
              self.InitSubItem['imgPath'] = res.data[0].path;
              self.InitSubItem['imgSystem'] = res.data[0].fileSystem;
              self.$forceUpdate();
            })

        },
        certainIcon(value){
            if(value.bgColor){
                this.InitSubItem['bgColor'] = value.bgColor;
            }
            if(value.icon){
                this.InitSubItem['icon']=value.icon;
            }
            if(value.system){
                this.InitSubItem['system'] = value.system;
            }
        },
        //选择流程定义
        processDefinition(subItem){
            var self_ = this
            let config={
                curVm: this,
                widthHeight: ['1000px', '600px'],
                zIndex:'99999',
                data:{}
            }
            this.isAddAppId(config)
            Dialog.openBpmDefDialog(config, function (self, data) {
                    var item = self
                    self_.$set(self_.InitSubItem, 'title', item.name)
                    self_.$set(self_.InitSubItem, 'defId', item.defId)

                }
            )
        },
        handDataAuths(key,queryAppId){
            if(!key){
                return;
            }

            var self=this;

            FormBoPermissionApi.getListByKey(key,queryAppId).then(res=>{
                let ary=res.data.list || [];
                self.dataAuthAry=ary.map(item=>{
                    return {label:item.name,value:item.permissionId};
                })
            })
        },
        chooseData(subItem) {
            var routeName = subItem.routeName
            if (!routeName) {
                this.$message.error(this.i18n('msa.routeName','请选择类型'))
                return
            }
            var self_ = this
            //解决方案 或者流程任务
            if (routeName == 'StartForm' || routeName == 'solTask') {
                var config={
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    data:{},
                }

                this.isAddAppId(config,"appId")
                Dialog.openBpmDefDialog(config, function (self, data) {
                        var item = self
                        self_.$set(subItem, 'title', item.name)
                        self_.$set(subItem, 'defId', item.defId)
                        self_.$set(subItem,'key',item.key)

                    }
                )
            } else if (routeName == 'CustomList') {
                var config={
                        data:{isDialog: 'NO'},
                        curVm: this,
                        widthHeight: ['800px', '600px']
                }
                this.isAddAppId(config,"queryAppId")
                Dialog.openFormBoListDialog(
                    config,
                    function (self, data) {
                        var item = data[0];
                        var queryAppId = sessionStorage.getItem(JsConstant.CUR_APP_ID_PORTAL);
                        self_.handDataAuths(item.key,queryAppId);
                        self_.$set(subItem, 'title', item.name)
                        self_.$set(subItem, 'key', item.key)
                        self_.$set(subItem, 'alias', item.formAlias)
                        self_.$set(subItem, 'addAlias', item.formAddAlias)
                        self_.$set(subItem, 'detailAlias', item.formDetailAlias)

                    }
                )
            } else if (routeName == 'CustomForm') {
                var config={
                    curVm: this,
                    data:{multiSelect:false},
                    widthHeight: ['800px', '600px'],
                }
                this.isAddAppId(config)
                DialogBox.openSoution(config,
                    function (self, data) {
                        var item = self
                        self_.$set(subItem, 'title', item.name)
                        self_.$set(subItem, 'alias', item.alias)

                    }
                )
            }else if (routeName == 'rxUreport') {
                var config={
                    component:UreportListDialog,
                    curVm:this,
                    title: this.i18n('portalMobile.selectUreport','选择ureport'),
                    data:{multiSelect:false},
                    widthHeight: ['800px', '600px']
                }
                this.isAddAppId(config)
                Util.open(config,function (action,data){
                    if(action!="ok"){
                        return;
                    }
                    self_.$set(subItem, 'alias', data[0].name)
                    self_.$set(subItem, 'title', data[0].name)
                });
            }else if(routeName =="appPortal"){
                //应用
                var conf = {
                    component: AppDialog,
                    data: {},
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    title: this.i18n('portalMobile.selectApp','选择应用')
                }
                Util.open(conf, function (action,data) {
                    if (action != 'ok') return;
                    self_.$set(subItem, 'appId', data.id)
                    self_.$set(subItem, 'title', this.$i18(data.name,'栏目入口名称'))
                });
            }else if(routeName =='customColumn'){
                    Util.open({
                        component: CustomPageColumnDialog,
                        curVm: this,
                        title: this.i18n('portalMobile.customColumnTitle','自定义页面栏目'),
                        widthHeight: ['750px', '500px'],
                        data: {
                            type:"1",
                        }
                    }, function (action, data) {
                        if(action!="ok") return;
                        self_.$set(subItem, 'appId', data.alias)
                        self_.$set(subItem, 'title', data.name)
                    });
            }

        },
        /**
         * 判断是否需要加上appId,
         * 需要时自动将appId放入config.data.appId中
         * @param config
         */
        isAddAppId(config,field){
            if (!field){
                field="appId"
            }
            //如果不能选择应用，直接使用当前appId
            if (!this.isCanSelectApp){
                config.data[field]=this.curApp.appId;
                return
            }

            config.data[field] = "0"
            if (this.InitSubItem.appId && this.InitSubItem.appId.length>0){
                //通过选择应用设置的appId,要在结束后清除sessionStorage
                config.data[field] = this.InitSubItem.appId[0].value;
                config.cancel=function (data){

                }
            }

        },
        openCustomView(initSubItem){
            var self_=this;
            var config = {
                curVm: this,
                widthHeight: ['800px', '600px'],
                component: CustomViewDialog,
                title: this.i18n('portalMobile.pageCustom','页面定制'),
                data:{
                    type:"drag",
                    isDefaultOpen:true
                },
            };
            this.isAddAppId(config)

            Util.open(config, function (action,data) {
                self_.$set(initSubItem, 'alias', data.alias);
                self_.$set(initSubItem, 'title', this.$i18(data.name,''));
                self_.$set(initSubItem, 'i18nJson',data.name);
                sessionStorage.removeItem("CUR_APP_ID");
            });
        },
        openCustomFunEdit(initSubItem){
            var self_=this;
            var config = {
                curVm: this,
                widthHeight: ['800px', '600px'],
                component: PortalJSMonacoEdit,
                title: this.i18n('portalMobile.customFun','自定义JS方法'),
                data:{type:"portalJS",language:"javascript",monacoValue:initSubItem.JSScript}
            };
            //判断选择应用是否启用
            if (this.isCanSelectApp){
                if (this.InitSubItem.appId && this.InitSubItem.appId.length>0){
                    config.data.appId=this.InitSubItem.appId[0].value;
                }
            }else {
                config.data.appId=this.curApp.appId;
            }
            Util.open(config, function (action,data) {
                if(action!='ok'){
                    return;
                }
                self_.$set(initSubItem, 'JSScript', data);
            });
        },
        handleSubmit(){
            var self_ = this;
            Util.closeWindow(self_, "ok",self_.InitSubItem);
        },
        cancel(){
            Util.closeWindow(this,'cancel');
        },
    },
    watch:{
        'InitSubItem.routeName':{
            handler: function (val,oldval) {
                //判断类型是否需要选择应用，判断是否为平台
                if(this.canSelAppRouters.includes(val) && this.isPlatform){
                    this.isCanSelectApp=true
                    //oldval!=null 表示不为第一次进入，当栏目类型时，清空应用
                    if (oldval!=null){
                        this.InitSubItem.appId=[]
                        this.InitSubItem.title=""
                        this.InitSubItem.i18nJson=""

                    }
                }else {

                    this.isCanSelectApp=false
                }
            },
            immediate: true
        },
        isPlatform:function (val) {
            if(this.canSelAppRouters.includes(this.InitSubItem.routeName) && val){
                this.isCanSelectApp=true
            }else {
                this.isCanSelectApp=false
            }
        }
    }
}
</script>

<style scoped>
.initSubItem-img{
    width: 50px;
    height: 50px;
    object-fit:contain;
}
.ant-upload-hint .up-title {
    display: inline-block;
    font-size: 14px;
    color: #333333;
    margin-top: 20px;
}
.upicon {
    font-size: 41px;
    color: #4285f4;
}
.self-dragger >>> .ant-upload-drag {
    height: 150px;
}
.self-dragger >>> .ant-upload-list {
    display: none;
}
.InsPortaMobileIconfont-programa{
    display: flex;
    position: relative;
}
.InsPortaMobileIconfont-programa input{
    flex: 1;
}
.InsPortaMobileIconfont-programa button{
    position: absolute;
    right: 0px;
    top: 0px;
    z-index: 1;
    background-color: #f5f7fa;
    border-radius: 0px 4px 4px 0px;
}
.InsPortaMobileIconfont{
    padding: 0px 20px;
    height: calc(100% - 70px);
    overflow: auto;
}
</style>